import pygame
from pygame.sprite import DirtySprite
from level_resources import LevelResources

class Animation(DirtySprite):
	def __init__(self, screen, location, frames, delays, repeat, mseconds):
		DirtySprite.__init__(self)

		self.frames = []
		self.running = False
		self.currentFrameIndex = -1
		self.image = None
		self.nrOfFrames = 0
		self.startingTime = 0
		self.finished = False

		self.screen = screen
		self.rect = location
		for frame in frames:
			self.frames.append(frame)
		self.delays = delays
		self.repeat = repeat
		self.mseconds = mseconds

		self.nrOfFrames = len(frames)

	def startAnimation(self):
		self.running = True
		self.finished = False
		self.currentFrameIndex = 0
		self.image = self.frames[0]
		self.startingFrameTime = pygame.time.get_ticks()
		self.startingTime = self.startingFrameTime

	def stopAnimation(self):
		self.running = False
		self.finished = True
		self.kill()

	def update(self):
		if not self.running:
			return None

		currentTime = pygame.time.get_ticks()
		if self.mseconds and currentTime - self.startingTime > self.mseconds:	#Time to stop anim
			self.stopAnimation()
			return None
		
		frameTime = currentTime - self.startingFrameTime
		if frameTime > self.delays[self.currentFrameIndex]:
			self.startingFrameTime = pygame.time.get_ticks()
			if self.currentFrameIndex + 1 < self.nrOfFrames:
				self.currentFrameIndex += 1
			else:
				if self.repeat == False and not self.mseconds:	#Stop repeating animation
					self.stopAnimation()
					return None
				else:
					self.currentFrameIndex = 0	#Repeat the animation

			self.image = self.frames[self.currentFrameIndex]



